import { doFetch, getFetch } from "./utils/doFetch";
import { history } from "umi";
const loginPath = "/user";

export async function getInitialState() {
  let token = localStorage.getItem("TOKENSTRING");
  const fetchUserInfo = async () => {
    try {
      const msg = await getFetch({
        url: "/user/info",
      });
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  if (!token) {
    history.push(loginPath);
  }

  if (history.location.pathname !== "/user/login" && token) {
    const currentUser = await fetchUserInfo();
    return {
      currentUser,
      fetchUserInfo,
    };
  } 
  return {
    currentUser: null,
    fetchUserInfo,
  };
}
